import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Like } from 'typeorm';
import { dishes } from './dishes.entity'; // 修改实体类命名

interface dishesInfo {
  merchant_id?: number,
  name?: string;
  sales?: number;
  rating?: number;
  status?: number;
  category_id?: number;
  is_featured?: number;
}

@Injectable()
export class DishesService {
  constructor(
    @InjectRepository(dishes) private readonly dishsRepository: Repository<dishes>, // 实体类引用
  ) { }
  /**
 * 查询菜品列表
 * @param data - 菜品属性，可为{ name, sales, rating, status, category_id, is_featured }
 * @returns 菜品列表
 */
  async find(data: dishesInfo): Promise<dishes[]> {
    // 定义允许的查询字段白名单
    const allowedFields: (keyof dishesInfo)[] = ['merchant_id', 'name', 'status', 'category_id', 'is_featured'];
    // 初始化查询条件
    const queryConditions: Partial<dishes> = {};
    if (data) {
      // 遍历输入数据，仅保留白名单中的字段
      for (const key in data) {
        if (data.hasOwnProperty(key) && allowedFields.includes(key as keyof dishesInfo)) {
          queryConditions[key as keyof dishesInfo] = data[key];
        }
      }
    } else {
      // 如果 data 为空或未定义，可以选择抛出错误或返回空结果
      console.warn('查询条件为空，将返回所有菜品');
    }
    try {
      // 执行查询
      return await this.dishsRepository.findBy(queryConditions);
    } catch (error) {
      // 抛出带有详细信息的错误
      throw new Error(`数据表查询错误: ${error.message}`);
    }
  }
    /**
* 查询菜品列表 分页
* @param info - 菜品列属性
* @returns 菜品列表+总数
*/
async findBy(info: any): Promise<any> {
  // 校验输入参数
  if (!Array.isArray(info.merchant_id) || info.merchant_id.some((id: number) => typeof id !== 'number')) {
    throw new Error('Invalid merchant_id: must be an array of numbers');
  }

  if (typeof info.pageSize !== 'number' || info.page < 1 || info.pageSize < 1) {
    throw new Error('Invalid pagination parameters: page and pageSize must be positive numbers');
  }

  let data = JSON.parse(JSON.stringify(info));
  delete data.merchant_id;
  delete data.page;
  delete data.pageSize;

  // 构建查询条件
  let whereConditions: any = {
    merchant_id: In(info.merchant_id),
  };

  if (data.name) {
    whereConditions.name = Like(`%${data.name}%`);
    delete data.name;
  }

  whereConditions = { ...whereConditions, ...data };
  // console.log(whereConditions);
  try {
    const [posts, total] = await this.dishsRepository.findAndCount({
      where: whereConditions,
      skip: (info.page - 1) * info.pageSize,
      order: {
        status: 'DESC',
      },
      take: info.pageSize,
    });

    return {
      data: posts,
      total,
      page: info.page,
      pageSize: info.pageSize,
      // ...其他分页信息
    };
  } catch (error) {
    throw new Error('Failed to fetch dishes');
  }
}

/**
 * 删除菜品列表
 * @param id - 要删除的菜品ID
 * @returns 操作结果
 */
async delete(id: number): Promise<object> {
  try {
    // 执行删除操作
    const result = await this.dishsRepository.delete(id);
    // 返回成功结果，包含删除操作的结果 
    return { success: true, ...result };
  } catch (error) { 
    // 记录详细的错误信息
    console.error('Error deleting dish:', error);
    // 抛出异常，表示删除菜品失败，并包含详细的错误信息
    throw new Error(`Failed to delete dish with ID ${id}: ${error.message}`);
  }
}

  /**
   * 新增菜品列表
   * @param info - 菜品信息
   * @returns 操作结果
   */
  async add(info: dishes): Promise<object> {
    try {
      const newMenu = this.dishsRepository.create(info);
      await this.dishsRepository.save(newMenu);
      return newMenu;
    } catch (error) {
      throw new Error('Failed to add menu');
    }
  }

  /**
   * 修改菜品列表
   * @param info - 菜品信息
   * @returns 操作结果
   */
  async edit(info: dishes): Promise<object> {
    try {
      const result = await this.dishsRepository.update(info.id, info);
      return result;
    } catch (error) {
      throw new Error('Failed to edit menu');
    }
  }

  /**
   * 菜品列表详情
   * @param id - 菜品ID
   * @returns 菜品详情
   */
  async detail(id: number): Promise<dishes | null> {
    try {
      return await this.dishsRepository.findOneBy({ id });
    } catch (error) {
      throw new Error('Failed to fetch menu details');
    }
  }
}
